import { login, logout, getInfo, getAuth } from '@/api/admin/adminUser';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { resetRouter } from '@/router';

const getDefaultState = () => {
    return {
        adminInfo: {
            userId: null,
            userName: ''
        },
        adminAuth: [],
        token: getToken()
    };
};

const state = getDefaultState();

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState());
    },
    SET_INFO: (state, adminInfo) => {
        state.adminInfo = adminInfo;
    },
    SET_AUTH: (state, auth) => {
        state.adminAuth = auth;
    }
};

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { userName, password } = userInfo;
        return new Promise((resolve, reject) => {
            login({ adminPhone: userName.trim(), adminPassword: password }).then(response => {
                resolve();
            }).catch(error => {
                reject(error);
            });
        });
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo().then(response => {
                const { data } = response;
                if (!data) {
                    reject('请重新登陆');
                }
                commit('SET_INFO', data);
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        });
    },

    getAuth({ commit, state }) {
        return new Promise((resolve, reject) => {
            getAuth().then(response => {
                const { data } = response;
                if (!data) {
                    reject('验证失败，请重新登陆');
                }
                commit('SET_AUTH', data);
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        });
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                removeToken(); // must remove  token  first
                resetRouter();
                commit('RESET_STATE');
                resolve();
            }).catch(error => {
                reject(error);
            });
        });
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            console.log('清除store');
            // removeToken(); // must remove  token  first
            commit('RESET_STATE');
            resolve();
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};

